<template>
  <div class="life-container">
    <el-row :gutter="20" style="margin:20px 0 0 0;">
      <el-col :span="4" style="font-size: 22px;font-weight: bolder;color: #333333">DRG分组数据</el-col>
      <el-col :span="20" style="text-align: end">
        <el-date-picker v-model="dateRange" end-placeholder="结束日期" format="YYYY-MM-DD" range-separator="-"
                        @change="handleDateChange"
                        start-placeholder="开始日期"
                        style="width: 280px" type="daterange" value-format="YYYY-MM-DD"></el-date-picker>
        <el-button icon="Plus" style="margin-left: 10px" type="primary" @click="handleNewGroup">新建DRG分组</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <!--   DRG分组数    -->
      <el-col :lg="6" :md="12" :sm="12" :xs="24" style="margin-top: 20px;">
        <el-card class="padding-top-bottom-16 padding-left-right-6 flex" style="width: 100%">
          <div class="flex justify-content-space-between" style="width: 100%">
            <div class="flex-auto">
              <div class="flex justify-content-space-between">
                <div class="title">DRG分组数</div>
              </div>
              <div class="flex align-center  justify-content-space-between">
                <div class="count">{{ cardData.drgInfoCount }}</div>
              </div>
              <div class="flex align-center  justify-content-space-between" v-if="cardData.drgMonthCount">
                <div style="color: #666;font-size: 15px">较上月 {{ cardData.drgMonthCount }}</div>
              </div>
            </div>

            <div class="indicator" :class="cardData.drgMonthRatio > 0 ? 'increase' : cardData.drgMonthRatio < 0 ? 'decrease' : 'fair'">{{ cardData.drgMonthRatio }}</div>

          </div>
        </el-card>
      </el-col>
      <!--   平均权重值    -->
      <el-col :lg="6" :md="12" :sm="12" :xs="24" style="margin-top: 20px;">
        <el-card class="padding-top-bottom-16 padding-left-right-6 flex" style="width: 100%">
          <div class="flex justify-content-space-between" style="width: 100%">
            <div class="flex-auto">
              <div class="flex justify-content-space-between">
                <div class="title">平均权重值</div>
              </div>
              <div class="flex align-center  justify-content-space-between">
                <div class="count">{{ cardData.drgWeightInfoAVGCount  }}</div>
              </div>
              <div class="flex align-center  justify-content-space-between"  v-if="cardData.drgWeightMonthAVGCount">
                <div style="color: #666;font-size: 15px">较上月 {{ cardData.drgWeightMonthAVGCount }}</div>

              </div>
            </div>
            <div :class="cardData.drgWeightMonthAVGRatio > 0 ? 'increase' : cardData.drgWeightMonthAVGRatio < 0 ? 'decrease' : 'fair'" class="indicator">{{ cardData.drgWeightMonthAVGRatio }}</div>
          </div>
        </el-card>
      </el-col>
      <!--   权重合计值    -->
      <el-col :lg="6" :md="12" :sm="12" :xs="24" style="margin-top: 20px;">
        <el-card class="padding-top-bottom-16 padding-left-right-6 flex" style="width: 100%">
          <div class="flex justify-content-space-between" style="width: 100%">
            <div class="flex-auto">
              <div class="flex justify-content-space-between">
                <div class="title">权重合计值</div>
              </div>
              <div class="flex align-center  justify-content-space-between">
                <div class="count">{{ cardData.drgWeightInfoSumCount }}</div>
              </div>
              <div class="flex align-center  justify-content-space-between"  v-if="cardData.drgWeightMonthSUMCount">
                <div style="color: #666;font-size: 15px">较上月 {{ cardData.drgWeightMonthSUMCount }}</div>
              </div>
            </div>

            <div :class="cardData.drgWeightMonthSUMRatio > 0 ? 'increase' : cardData.drgWeightMonthSUMRatio < 0 ? 'decrease' : 'fair'" class="indicator">{{ cardData.drgWeightMonthSUMRatio }}</div>
          </div>
        </el-card>
      </el-col>
      <!--   平均住院天数    -->
      <el-col :lg="6" :md="12" :sm="12" :xs="24" style="margin-top: 20px;">
        <el-card class="padding-top-bottom-16 padding-left-right-6 flex" style="width: 100%">
          <div class="flex justify-content-space-between" style="width: 100%">
            <div class="flex-auto">
              <div class="flex justify-content-space-between">
                <div class="title">平均住院天数</div>
              </div>
              <div class="flex align-center  justify-content-space-between">
                <div class="count">{{ cardData.drgadmDayCount }}</div>
              </div>
              <div class="flex align-center  justify-content-space-between"   v-if="cardData.drgMonthADMDayCount">
                <div style="color: #666;font-size: 15px">较上月 {{ cardData.drgMonthADMDayCount }}</div>
              </div>
            </div>

            <div :class="cardData.drgMonthADMDayRatio > 0 ? 'increase' : cardData.drgMonthADMDayRatio < 0 ? 'decrease' : 'fair'" class="indicator">{{ cardData.drgMonthADMDayRatio }}</div>
          </div>
        </el-card>
      </el-col>
      <!--   card结束    -->
    </el-row>
    <div class="select-container flex">
      <div class="department-cmi-ranking flex-auto" style="margin-right: 10px;position: relative">
        <EchartsComponent :options="chartOption2" class="charts-common flex-auto">
          <div class="flex" style="position: absolute;top: -10px;right:0;z-index: 10;">
            <el-button :type="selectedButton === 'MDC' ? 'primary' : ''" @click="handleButtonClick('MDC')">MDC</el-button>
            <el-button :type="selectedButton === 'ADRG' ? 'primary' : ''" @click="handleButtonClick('ADRG')">ADRG</el-button>
          </div>
        </EchartsComponent>
      </div>
      <div class="trend-analysis flex-auto" style="margin-left: 10px">
        <EchartsComponent :options="chartOption1" class="charts-common flex-auto"></EchartsComponent>
      </div>
    </div>
    <div class="select-container padding-20" style="background: #FFFFFF;">
         <div class="flex justify-content-space-between align-center">
           <div class="sub-title" style="font-weight: bolder;color: #333333">患者DRG分组历史</div>
           <div class="flex align-center justify-content-end ">
             <el-input v-model="partRequest.admNumber" clearable placeholder="住院号"  style="width: 240px"></el-input>
             <el-input v-model="partRequest.userName" clearable placeholder="患者姓名" style="width: 240px;margin: 0 10px"></el-input>
             <el-input v-model="partRequest.departMentName" clearable placeholder="科室"  style="width: 240px;margin: 0 10px"></el-input>
             <el-input v-model="partRequest.drgName" clearable placeholder="DRG组名"  style="width: 240px"></el-input>
             <el-button icon="search" style="margin: 0 10px" type="primary" @click="getUserByName">搜索</el-button>
           </div>
         </div>
      <el-table :data="tableData" style="margin-top: 20px">
        <el-table-column align="center" label="患者ID" prop="patientId">
          <template #default="{ row }">
            <div style="font-weight: bolder;color: #333333">{{ row.userId }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="姓名" prop="userName"/>
        <el-table-column align="center" label="住院号" prop="admNumber"/>
        <el-table-column align="center" label="入院日期" prop="admTime"/>
        <el-table-column align="center" label="DRG分组" prop="drgCode"/>
        <el-table-column align="center" label="RW权重" prop="drgWeight"/>
        <el-table-column align="center" label="是否有并发症" prop="isDiseaseTableName">
          <template #default="{ row }">
            <div v-if="row.isDiseaseTableName" class="has">是</div>
            <div v-else class="no">否</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link size="small" type="primary" @click="userInfoDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="position:relative; ">
        <pagination
            v-model:limit="partRequest.pageSize"
            v-model:page="partRequest.pageNumber"
            :total="partRequest.totalCount"
            @pagination="getPaginationList"/>
      </div>
    </div>
    <el-dialog :model-value="visible" title="患者信息详情" @close="handleClose" >
      <el-form ref="formRef" :model="formData"  label-position="top" :disabled="true">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="病人ID" prop="userId">
              <el-input v-model="formData.userId" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="formData.userName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主治医生" prop="doctorName">
              <el-input v-model="formData.doctorName"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手机号码" prop="userPhone">
              <el-input v-model="formData.userPhone"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="formData.age"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="住院号码" prop="admNumber">
              <el-input v-model="formData.admNumber"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="住院时间" prop="admTime">
              <el-date-picker v-model="formData.admTime" placeholder="请选择住院时间" style="width: 100%" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出院时间" prop="outTime">
              <el-date-picker v-model="formData.outTime" placeholder="请选择出院时间" style="width: 100%" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="住院天数" prop="admDay">
              <el-input v-model="formData.admDay"  style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="Male"/>
                <el-option label="女" value="female"/>
                <el-option label="未知" value="Unknown"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="是否新生儿" prop="isNoun">
              <el-switch v-model="formData.isNoun"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期" prop="dob">
              <el-date-picker v-model="formData.dob" placeholder="请选择出生日期" style="width: 100%" type="date" value-format="YYYY-MM-DD"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标准权重" prop="drgWeight">
              <el-input v-model="formData.drgWeight"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="MDC父级标识" prop="mdcCode">
              <el-input v-model="formData.mdcCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="ADRG分组标识" prop="drgOrganizationKey">
              <el-input v-model="formData.drgOrganizationKey"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="创建时间" prop="creationTime">
              <el-date-picker v-model="formData.creationTime" placeholder="请选择创建时间" style="width: 100%" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="DRG特殊分组Code标识" prop="espCode">
              <el-input v-model="formData.espCode"/>
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
<!--      <template #footer>-->
<!--        <div class="dialog-footer">-->
<!--          <el-button @click="handleClose">取 消</el-button>-->
<!--          <el-button :loading="submitLoading" type="primary" @click="handleSubmit">确 定</el-button>-->
<!--        </div>-->
<!--      </template>-->
    </el-dialog>
  </div>
</template>
<script setup>
import {ref,} from 'vue';
import {Search, Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import EchartsComponent from "@/components/ECharts/index.vue";
import DateUtils from "@/utils/utils.js";
import {getCountData, getCountRWorCMI, getDRGCountRatio, getDRGUserList, getUserDetail} from "@/api/drg/drg.js";
const selectedButton = ref('MDC');
import { useRouter } from 'vue-router'
const router = useRouter();
const cardData = ref({
  drgInfoCount: 0,
  drgMonthCount: 0,
  drgMonthRatio: 0,
  drgWeightInfoAVGCount: 0,
  drgWeightMonthAVGCount: 0,
  drgWeightMonthAVGRatio: 0,
  drgWeightInfoSumCount: 0,
  drgWeightMonthSUMCount: 0,
  drgWeightMonthSUMRatio: 0,
  drgadmDayCount: 0,
  drgMonthADMDayCount: 0,
  drgMonthADMDayRatio: 0
});
const dateRange = ref([
  DateUtils.getFirstDayOfMonth(),
  DateUtils.formatDate(DateUtils.now(), "yyyy-MM-dd")
]);
const chartOption1 = ref({
  title: {text: 'RW与CMI指数趋势'},
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    data: ['CMI指数', 'RW值指数']
  },
  xAxis: [
    {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月'],
      axisLabel: {
        color: '#666'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee'
        }
      }
    }
  ],
  series: [
    {
      name: 'CMI指数',
      type: 'line',
      data: [12, 13, 11, 14, 13, 12],
      itemStyle: {color: '#5dc231'},
    },
    {
      name: 'RW值指数',
      type: 'line',

      itemStyle: {color: '#176105'},
      data: [8, 9, 9, 9, 13, 14],
    }
  ]
});
const chartOption2 = ref({
  title: { text: 'DRG分组数量占比分布' },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  series: [
    {
      name: '疾病分布',
      type: 'pie',
      radius: ['30%', '60%'], // 环形图内外半径
      avoidLabelOverlap: false, // 允许标签重叠（避免标签被隐藏）
      label: {
        show: true,
        position: 'outside', // 标签位置在外部
        formatter: '{b}: {d}%',
        distance: 2, // 标签与引导线末端的距离（贴近引导线）
        fontSize: 12,
        color: '#333',
        align: 'left' // 标签左对齐，更贴合引导线
      },
      labelLine: {
        show: true,
        length: 10, // 第一段引导线长度（从扇区到转折点）
        length2: 15, // 第二段引导线长度（从转折点到标签）
        smooth: false, // 关闭平滑，让引导线更平直
        lineStyle: {
          color: '#999'
        }
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '16',
          fontWeight: 'bold'
        }
      },
      data: [
        { value: 100, name: '呼吸系统疾病' },
        { value: 80, name: '循环系统疾病' },
        { value: 60, name: '消化系统疾病' },
        { value: 40, name: '神经系统疾病' },
        { value: 20, name: '内分泌疾病' }
      ]
    }
  ],
  label: {
    show: true, // 显示标签（引导线依赖标签存在）
    position: 'outside', // 标签在扇形外部（引导线连接外部标签）
    fontSize: 12, // 标签字体大小
    color: '#666', // 标签颜色
    formatter: '{b}: {d}%' // 显示名称和百分比
  },
});
const tableData = ref([]);
const partRequest = ref({
  admNumber: '', // 住院号码
  userName: '', // 患者名称
  drgName: '', // DRG分组名称
  departMentName:"", // 科室名称
  pageNumber: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0
});
const visible = ref(false);
const handleClose = () => {
  visible.value = false;
};
const formData = ref({});
const getTableDataPageList = async (requestData) => {
  const {pageNumber, pageSize, userName, drgName,departMentName, admNumber} = requestData;
  let result = await getDRGUserList({pageNumber, pageSize, userName, drgName,departMentName, admNumber});
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200) {
    const {pageNumber, pageSize, totalCount, totalPages, items} = data;
    partRequest.value.pageNumber = pageNumber;
    partRequest.value.pageSize = pageSize;
    partRequest.value.totalCount = totalCount;
    partRequest.value.totalPages = totalPages;
    tableData.value = items;
  }
};
const getUserDetailById = async (userId) => {
  let result = await getUserDetail({guid:userId});
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200) {
    formData.value = data;
  }
};
const getDRGCountData = async (reqData) => {
  let result = await getCountData({
    startTime: reqData[0],
    endTime: reqData[1],
  });
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200) {
    cardData.value = data;
  }
};
const userInfoDetail = (item)=>{
  console.log('item',item)
  // visible.value = true;
  // getUserDetailById(item.id);
  router.push({path: '/drg/display', query: {id: item.id}})
};
const handleDateChange = () => {
  getDRGCountData(dateRange.value);
  getCountRWorCMIInfos({
    startTime: dateRange.value[0],
    endTime: dateRange.value[1],
  });
  getDRGCountRatioInfos({
    drgTypeName: selectedButton.value,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1],
  });
};
const getPaginationList = (pageData) => {
  partRequest.value.pageNumber = pageData.page;
  partRequest.value.pageSize = pageData.limit;
  getTableDataPageList(partRequest.value);
};
const getUserByName = () => {
  partRequest.value.pageNumber = 1;
  getTableDataPageList(partRequest.value);
};
const handleButtonClick = (buttonType) => {
  selectedButton.value = buttonType;
  getDRGCountRatioInfos({
    drgTypeName: selectedButton.value,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1],
  });
};
// 获取RW与CMI指数趋势
const getCountRWorCMIInfos = async (reqData) => {
  let result = await getCountRWorCMI(reqData);
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200) {
    const rwInfoList = [];
    const cmiInfoList = [];
    const dateList = [];
     data.forEach(item => {
      rwInfoList.push(item.rwWeightValue);
      cmiInfoList.push(item.cmiValue);
      dateList.push(item.departMenName);
    });
    chartOption1.value.series[0].data = cmiInfoList;
    chartOption1.value.series[1].data = rwInfoList;
    chartOption1.value.xAxis[0].data = dateList;
  }
};
// DRG分组数据占比分布
const getDRGCountRatioInfos = async (reqData) => {
  let result = await getDRGCountRatio({
    drgTypeName: reqData.drgTypeName,
    startTime: reqData.startTime,
    endTime: reqData.endTime,
  });
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200) {
    let array = [];
    data.forEach(item => {
      array.push({name: item.mdcName, value: item.mdcCodeValue});
    });
     chartOption2.value.series[0].data = array;
  }
};
const handleNewGroup = ()=>{
   router.push({path: '/drg/input'})
}
getTableDataPageList(partRequest.value);
getDRGCountData(dateRange.value); // 获取统计面板数据
getCountRWorCMIInfos({ // 获取RW与CMI指数趋势
  startTime: dateRange.value[0],
  endTime: dateRange.value[1],
});
getDRGCountRatioInfos({
  drgTypeName: selectedButton.value,
  startTime: dateRange.value[0],
  endTime: dateRange.value[1],
});
</script>
<style lang='scss' scoped>
.life-container {
  height: calc(100% - 40px);
  box-sizing: border-box;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  padding: 20px;
  border-radius: 5px;

  .el-card {
    border-radius: 13px;
    border: none;
  }

  :deep(.el-card__body) {
    width: 100%;
  }

  .title {
    color: #898F9A;
  }

  .count {
    padding: 14px 0;
    color: #464646;
    font-weight: bold;
    font-size: 22px;
  }

  .indicator {
    height: 100%;
  }

  .increase {
    color: #00C94F;
  }

  .decrease {
    color: #FF3643;
  }

  .fair {
    color: #8F95A1;
  }

  .select-container {
    margin-top: 20px;
    border-radius: 10px;

    .trend-analysis {
    }

    .department-cmi-ranking {

    }
  }

  .charts-common {
    border-radius: 10px;
    padding: 20px;
    box-sizing: border-box;
    height: 400px;
  }

  .table-title {
    color: #333333;
    font-weight: bolder;
    letter-spacing: 1px;
  }

  .has {
    margin: 0 auto;
    text-align: center;
    color: #188e4d;
    background-color: rgba(0, 201, 79, 0.34);
    width: fit-content;
    height: fit-content;
    border-radius: 10px;
    padding: 0 6px;
    font-size: 12px
  }

  .no {
    margin: 0 auto;
    text-align: center;
    color: #000000;
    background-color: rgba(158, 187, 170, 0.34);
    width: fit-content;
    height: fit-content;
    border-radius: 10px;
    padding: 0 6px;
    font-size: 12px
  }


}


</style>
